package com.rn.simple.controller;

import com.rn.simple.common.ContractExecutor;
import com.rn.simple.loader.CusJavaCompiler;
import com.rn.simple.loader.FileUtils;
import com.rn.simple.loader.HackSystem;
import com.rn.simple.loader.JavaClassExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Description：样例控制器
 *
 * @author rannuo
 * @date 2019/11/9
 */
@RestController
@RequestMapping("simple")
public class SimpleController {

    @Autowired
    private ContractExecutor contractExecutor;

    @GetMapping
    public String simple() {
        contractExecutor.test();
        return "simple";
    }

    @GetMapping("testHotSwapClassLoader")
    public String testHotSwapClassLoader() {
        String path = "D:\\JavaDev\\IDEA_J\\simple\\src\\main\\java\\com\\rn\\simple\\common\\MainClass";
        // 删除旧的.class
        try {
            FileUtils.deleteIfExists(path + ".class");
        } catch (IOException e) {
            e.printStackTrace(HackSystem.out);
        }
        boolean compile = CusJavaCompiler.compile(path + ".java");
        if (!compile) {
            return "编译失败";
        }
        byte[] bytes = new byte[0];
        try (InputStream is = new FileInputStream(path + ".class")) {
            bytes = new byte[is.available()];
            int read = is.read(bytes);
        } catch (IOException e) {
            e.printStackTrace(HackSystem.out);
        }

        return JavaClassExecutor.execute(bytes, "test", new String[]{"testHotSwapClassLoader"});
    }

}
